//
//  UserFindPasswordViewController.swift
//  SitPosition
//
//  Created by apple on 2018/12/31.
//  Copyright © 2018 apple. All rights reserved.
//

import Foundation
import UIKit
import Cartography


class UserFindPasswordViewController : UserLoginRegistrationBaseViewController {
    
    // MARK: - Properties
    
    // 验证码
    static fileprivate var verifyCode: PhoneVerifyCode? = nil
    
    
    // MARK: - Subviews
    
    // 手机号
    lazy var phoneTextfield: TextFieldWithLRView = {
        return _buildTextField(placeholder: Strings.logonPhonePlaceholder,
                               leftView: UIImageView(image: UIImage(named: "logon_phone")))
    }()
    
    // 验证码
    lazy var verifyCodeTextfield: TextFieldWithLRView = {
        return _buildTextField(placeholder: Strings.logonVerifyCodePlaceholder,
                               leftView: UIImageView(image: UIImage(named: "logon_key")))
    }()
    
    // 下一步按钮
    lazy var nextButton: UserLogonStateButton = {
        let button = UserLogonStateButton(title: Strings.logonNext)
        button.addTarget(self, action: #selector(_step2Next), for: UIControl.Event.touchUpInside)
        return button
    }()
    
    let seperator1 = UIView.colored(Theme.Color.primaryBlueSeperatorColor)
    let seperator2 = UIView.colored(Theme.Color.primaryBlueSeperatorColor)
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        gk_navLeftBarButtonItem = UIBarButtonItem(imageName: "ic_nav_back", target: self, action: #selector(_backButtonTapped))
        
        // 设置Views
        view.addSubviews([
            titleLabel,
            phoneTextfield,
            seperator1,
            verifyCodeTextfield,
            getVerifyCodeButton,
            seperator2,
            nextButton
        ])
        _setupContraints()
        
        // 初始化Views
        titleLabel.text = Strings.logonFindPassword
        getVerifyCodeButton.addTarget(self, action: #selector(_getVerifyCode), for: UIControl.Event.touchUpInside)
    }
}

// MARK: Private Methods

extension UserFindPasswordViewController {
    
    // 设置视图约束
    func _setupContraints() {
        // titleLabel
        constrain(titleLabel, gk_navigationBar, view) { v, sibling, parent in
            v.top == sibling.bottom + 34
            v.left == parent.left + 40
            v.right == parent.right - 40
            v.height == 25
        }
        
        // phoneTextfield
        let kTextfieldHeight: CGFloat = 36
        constrain(phoneTextfield, titleLabel) { v, sibling in
            v.top == sibling.bottom + 48
            v.left == sibling.left
            v.height == kTextfieldHeight
            v.right == sibling.right
        }
        
        // seperator1
        constrain(seperator1, phoneTextfield) { v, sibling in
            v.top == sibling.bottom+4
            v.left == sibling.left
            v.right == sibling.right
            v.height == 1
        }
        
        // verifyCodeTextfield
        constrain(verifyCodeTextfield, seperator1) { v, sibling in
            v.top == sibling.bottom + 37
            v.left == sibling.left
            v.height == kTextfieldHeight
            v.right == sibling.right - 110
        }
        
        // seperator2
        constrain(seperator2, verifyCodeTextfield) { v, sibling in
            v.top == sibling.bottom + 4
            v.left == sibling.left
            v.right == sibling.right
            v.height == 1
        }
        
        // getVerifyCodeButton
        constrain(getVerifyCodeButton, seperator1, seperator2) { v, sibling, sibling2 in
            v.right == sibling.right
            v.bottom == sibling2.bottom
            v.width == 80
            v.height == 35
        }
        
        // nextButton
        constrain(nextButton, seperator2) { v, sibling in
            v.top == sibling.bottom + 30
            v.left == sibling.left
            v.width == 200
            v.height == 55
        }
    }
    
    // 返回按钮点击事件
    @objc func _backButtonTapped() {
        backCallback()
    }
    
    // 获取验证码
    @objc func _getVerifyCode() {
        // 校验参数
        guard let mobile = phoneTextfield.text, !mobile.isEmpty else {
            view.makeToast(Strings.logonPhoneEmpty)
            return
        }
        
        // 获取验证码
        view.makeToastActivity(.center)
        NetworkClient.instance.fetchVerifyCode(mobile: mobile, type: "password", success: { [weak self] (data) in
            guard let sself = self else { return }
            sself.view.hideToastActivity()
            
            guard let data_ = data else {
                sself.view.makeToast(Strings.logonFailedSendPhoneCode)
                return
            }
            do {
                let decoder: JSONDecoder = JSONDecoder()
                let verifyCode: PhoneVerifyCode = try decoder.decode(PhoneVerifyCode.self, from: data_)
                UserFindPasswordViewController.verifyCode = verifyCode
                sself._onGotPhoneVerifyCode()
            } catch {
                sself.view.makeToast(error.localizedDescription)
            }
        }) { [weak self] (error) in
            guard let sself = self else { return }
            sself.view.hideToastActivity()
            
            // 显示错误
            sself.view.makeToast(error?.networkErrorMessage ?? Strings.logonFailedSendPhoneCode)
        }
    }
    
    // 获取验证码的后处理流程
    func _onGotPhoneVerifyCode() {
        // TODO: 获取验证码的后处理流程
    }
    
    // 下一步
    @objc func _step2Next() {
        // 前端校验用户输入
        guard let mobile = phoneTextfield.text, !mobile.isEmpty,
            let plaintextCode = verifyCodeTextfield.text, !plaintextCode.isEmpty else {
            view.makeToast(Strings.logonPhoneCodeEmpty)
            return
        }
        guard let verifyCode = UserFindPasswordViewController.verifyCode,
            verifyCode.code == plaintextCode.md5() else {
            view.makeToast(Strings.logonVerifyCodeWrong)
            return
        }
        
        // 进入下一步
        let setpwdVC = UserSetPasswordViewController()
        setpwdVC.backCallback = { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        setpwdVC.onSettedupBlock = { [weak self] newPassword in
            UserManager.manager.resetPassword(mobile: mobile, code: plaintextCode, password: newPassword, completion: { (error) in
                guard error == nil else {
                    topmostView()?.makeToast(error?.networkErrorMessage ?? Strings.logonFailedResetPassword)
                    return
                }
                topmostView()?.makeToast(Strings.logonSuccessResetPassword,
                                         duration: Theme.Toast.normalDuration,
                                         position: .center)
                self?.navigationController?.popToRootViewController(animated: true)
            })
        }
        navigationController?.pushViewController(setpwdVC, animated: true)
        
    }
}
